package cn.geminis.core.util;

import cn.geminis.core.exception.CommonException;
import lombok.NonNull;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * @author Allen
 */
public class DateUtils {

    private DateUtils() {
    }

    public static String toString(@NonNull Calendar calendar, @NonNull String format) {
        return toString(calendar.getTime(), format);
    }

    public static String toString(@NonNull Calendar calendar, @NonNull String format, @NonNull Locale locale) {
        return toString(calendar.getTime(), format, locale);
    }

    public static String toString(@NonNull Date date, @NonNull String format) {
        return toString(date, format, Locale.getDefault(Locale.Category.FORMAT));
    }

    public static String toString(@NonNull Date date, @NonNull String format, @NonNull Locale locale) {
        var dateFormat = new SimpleDateFormat(format, locale);
        return dateFormat.format(date);
    }

    public static String toString(@NonNull LocalDateTime date, @NonNull String format) {
        var formatter = DateTimeFormatter.ofPattern(format);
        return date.format(formatter);
    }

    public static Date parseDate(@NonNull String value, @NonNull String format) {
        var dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(value);
        } catch (ParseException e) {
            throw new CommonException("日期解析错误", e);
        }
    }

    public static Calendar parseCalendar(@NonNull String value, @NonNull String format) {
        var calendar = Calendar.getInstance();
        calendar.setTime(parseDate(value, format));
        return calendar;
    }

    public static LocalDateTime parseLocalDateTime(@NonNull String value, @NonNull String format) {
        var formatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(value, formatter);
    }

    public static LocalDateTime toLocalDateTime(@NonNull Date date) {
        var instant = date.toInstant();
        var zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    public static Date toDate(@NonNull LocalDateTime date) {
        var zone = ZoneId.systemDefault();
        var instant = date.atZone(zone).toInstant();
        return Date.from(instant);
    }
}
